package com.ybw.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ybw.dao.ModuleMapper;
import com.ybw.dao.PermissionMapper;
import com.ybw.dao.ResourceMapper;
import com.ybw.entity.Module;
import com.ybw.entity.ModuleRPermission;
import com.ybw.entity.Permission;
import com.ybw.entity.Resource;
import com.ybw.excelEntity.ModulePermissionExcel;
import com.ybw.utils.ExcelListener;
import org.apache.poi.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;

@Controller
public class CentralController {
    static Map<String, String> obsExcelMap = new HashMap<>();
    static Map<String, String> oaExcelMap = new HashMap<>();

    static {
        obsExcelMap.put("1", "收货联系人");
        obsExcelMap.put("2", "项目代码");
        obsExcelMap.put("3", "运单号");
        obsExcelMap.put("4", "应付人工数");
        obsExcelMap.put("5", "收货地址类型");
        obsExcelMap.put("6", "发货地址类型");
        obsExcelMap.put("7", "是否加急");
        obsExcelMap.put("8", "应付重泡货");
        obsExcelMap.put("9", "支出运输方式");
        obsExcelMap.put("10", "单位2");
        obsExcelMap.put("11", "支出数量2");
        obsExcelMap.put("12", "单位1");
        obsExcelMap.put("13", "支出数量1");
        obsExcelMap.put("14", "运单计费车型");
        obsExcelMap.put("15", "支出体积");
        obsExcelMap.put("16", "支出重量");
        obsExcelMap.put("17", "业务类型");
        obsExcelMap.put("18", "计划到货时间");
        obsExcelMap.put("19", "计划提货时间");
        obsExcelMap.put("20", "收货汇总地址");
        obsExcelMap.put("21", "收货区县");
        obsExcelMap.put("22", "收货城市");
        obsExcelMap.put("23", "发货汇总地址");
        obsExcelMap.put("24", "发货区县");
        obsExcelMap.put("25", "发货城市");
        obsExcelMap.put("26", "收货地址代码");
        obsExcelMap.put("27", "发货地址代码");
        obsExcelMap.put("28", "客户代码");
        obsExcelMap.put("29", "子单创建时间");
        obsExcelMap.put("30", "段类型");
        obsExcelMap.put("31", "子单号");
        obsExcelMap.put("32", "合并客户查询号");
        obsExcelMap.put("33", "应付计费标识");
        obsExcelMap.put("34", "计费时间");
        obsExcelMap.put("35", "账单");
        obsExcelMap.put("36", "账单状态");
        obsExcelMap.put("37", "账单期间");
        obsExcelMap.put("38", "提货费税额");
        obsExcelMap.put("39", "含税提货费");
        obsExcelMap.put("40", "短驳费税额");
        obsExcelMap.put("41", "含税短驳费");
        obsExcelMap.put("42", "干线费税额");
        obsExcelMap.put("43", "含税干线费");
        obsExcelMap.put("44", "应付配送费税额");
        obsExcelMap.put("45", "含税应付配送费");
        obsExcelMap.put("46", "临时费税额");
        obsExcelMap.put("47", "含税临时费");
        obsExcelMap.put("48", "运费税额");
        obsExcelMap.put("49", "含税运费");
        obsExcelMap.put("50", "专车费税额");
        obsExcelMap.put("51", "含税专车费");
        obsExcelMap.put("52", "人工费税额");
        obsExcelMap.put("53", "含税人工费");
        obsExcelMap.put("54", "装车费税额");
        obsExcelMap.put("55", "含税装车费");
        obsExcelMap.put("56", "卸货费税额");
        obsExcelMap.put("57", "含税卸货费");
        obsExcelMap.put("58", "回单费税额");
        obsExcelMap.put("59", "含税回单费");
        obsExcelMap.put("60", "空运费税额");
        obsExcelMap.put("61", "含税空运费");
        obsExcelMap.put("62", "保险费税额");
        obsExcelMap.put("63", "含税保险费");
        obsExcelMap.put("64", "超长费税额");
        obsExcelMap.put("65", "含税超长费");
        obsExcelMap.put("66", "上楼费税额");
        obsExcelMap.put("67", "含税上楼费");
        obsExcelMap.put("68", "清点费税额");
        obsExcelMap.put("69", "含税清点费");
        obsExcelMap.put("70", "翻托费税额");
        obsExcelMap.put("71", "含税翻托费");
        obsExcelMap.put("72", "包装费税额");
        obsExcelMap.put("73", "含税包装费");
        obsExcelMap.put("74", "税额小计");
        obsExcelMap.put("75", "含税小计");
        obsExcelMap.put("76", "备注");

        oaExcelMap.put("1", "客户查询号");
        oaExcelMap.put("2", "线路名称");
        oaExcelMap.put("3", "收货省份");
        oaExcelMap.put("4", "创建时间");
        oaExcelMap.put("5", "应收结算方式");
        oaExcelMap.put("6", "订单号");
        oaExcelMap.put("7", "客户代码");
        oaExcelMap.put("8", "收入运输方式");
        oaExcelMap.put("9", "部门");
        oaExcelMap.put("10", "数量1");
        oaExcelMap.put("11", "数量2");
        oaExcelMap.put("12", "收入重量");
        oaExcelMap.put("13", "收入体积");
        oaExcelMap.put("14", "计费车型");
        oaExcelMap.put("15", "计划提货时间");
        oaExcelMap.put("16", "发货城市");
        oaExcelMap.put("17", "发货区县");
        oaExcelMap.put("18", "计划到货时间");
        oaExcelMap.put("19", "发货地址公司");
        oaExcelMap.put("20", "收货地址公司");
        oaExcelMap.put("21", "计费时间");
        oaExcelMap.put("22", "账单");
        oaExcelMap.put("23", "账单状态");
        oaExcelMap.put("24", "账单期间");
        oaExcelMap.put("25", "不含税运费");
        oaExcelMap.put("26", "运费税额");
        oaExcelMap.put("27", "含税运费");
        oaExcelMap.put("28", "不含税临时费");
        oaExcelMap.put("29", "临时费税额");
        oaExcelMap.put("30", "含税临时费");
        oaExcelMap.put("31", "不含税小计");
        oaExcelMap.put("32", "税额小计");
        oaExcelMap.put("33", "含税小计");
        oaExcelMap.put("34", "备注");
    }


    @Autowired
    ModuleMapper moduleMapper;
    @Autowired
    PermissionMapper permissionMapper;
    @Autowired
    ResourceMapper resourceMapper;

    List<Permission> permissionList;
    List<Module> moduleList;
    List<Resource> resourceList;

    @PostMapping("/1")//根据excel生成info_module_permission
    public String _1(){
        try {
            //1.读取数据库info_permission、info_module
            load();
            //2.读取excel表格到list变量
            FileInputStream fis =new FileInputStream(new File("D:\\Users\\yangbowen3\\OneDriver\\OneDrive - 上海商汤临港智能科技有限公司\\MM1.0开发\\权限管理表格\\module_r_permission_v1.xlsx"));
            ExcelListener excelListener=new ExcelListener();
            EasyExcel.read(fis,excelListener).sheet().doRead();
            List<JSONObject> JSONObjects=excelListener.getDataList();
            List<ModulePermissionExcel> MPEs=new ArrayList<>();
            JSONObjects.forEach(e->{
                MPEs.add(JSONObject.toJavaObject(e,ModulePermissionExcel.class));
            });
            //3.构造info_module_permission条目的对象列表
            List<ModuleRPermission> MRPs=new ArrayList<>();
           for(ModulePermissionExcel mpe : MPEs){
               ModuleRPermission mrp=new ModuleRPermission();

               Long permissionId=permissionList.stream().filter(e1->mpe.getUrl().equals(
                       resourceList.stream().filter(e2->e1.getResourceId().equals(
                               e2.getResourceId()
                       )).findAny().get().getUrlPrefix()
               )).findAny().get().getPermissionId();
               mrp.setPermissionId(permissionId);

               Long moduleId=moduleList.stream().filter(e1->e1.getCode().equals(
                       mpe.getModuleCode()
               )).findAny().orElse(new Module(0L,null,null)).getModuleId();
               mrp.setModuleId(moduleId);

               int typeId=0;
               switch(mpe.getModuleType()){
                   case "QUERY":
                       typeId=101;
                       break;
                   case "EDIT":
                       typeId=102;
                       break;
                   case "USE":
                       typeId=103;
                       break;
                   case "EXPORT":
                       typeId=105;
                       break;
               }
               mrp.setTypeId(typeId);
               MRPs.add(mrp);
           }

            //4.构造sql语句,存储到data2.json
            StringBuffer sb=new StringBuffer();
            Long id=1L;
            for(ModuleRPermission e : MRPs) {
                    sb.append("insert into user.info_module_permission(id,permission_id,module_id,type_id) values(")
                            .append(id)
                            .append(",")
                            .append(e.getPermissionId())
                            .append(",")
                            .append(e.getModuleId())
                            .append(",")
                            .append(e.getTypeId())
                            .append(");\n");
                    id++;
                    }
            FileOutputStream fos=new FileOutputStream(new File("C:\\COC1.1-prod\\JSON2.0\\src\\main\\resources\\data2.json"));
            fos.write(sb.toString().getBytes(StandardCharsets.UTF_8));
            fos.flush();
            fos.close();

            return "done";
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }

    @PostMapping("/2/{fileName}")//把excel转化成文本文件(便于git比较差异)(应收)
    public String _2(@PathVariable("fileName") String fileName) {
        try {
            String type;
            Map<String, String> excelMap = new HashMap<>();
            if (fileName.contains("obs")) {
                excelMap = obsExcelMap;
                type = "obs";
            }else{
                excelMap = oaExcelMap;
                type = "oa";
            }

            StringBuffer sb = new StringBuffer();
            FileInputStream fis = new FileInputStream(new File("C:\\Users\\yangbowen\\Downloads\\" + fileName + ".xlsx"));
            ExcelListener excelListener = new ExcelListener();
            EasyExcel.read(fis, excelListener).sheet().doRead();
            List<JSONObject> JSONObjects = excelListener.getDataList();

            Comparator comparator;
            if ("obs".equals(type)) {

                comparator = new Comparator<JSONObject>() {
                    @Override
                    public int compare(JSONObject o1, JSONObject o2) {
                        if (o1.get("31").toString().compareTo(o2.get("31").toString()) > 0)
                            return 1;
                        else if(o1.get("31").toString().compareTo(o2.get("31").toString()) == 0)
                            return 0;
                        else return -1;
                    }
                };
            }else{

                comparator = new Comparator<JSONObject>() {
                    @Override
                    public int compare(JSONObject o1, JSONObject o2) {
                        if (o1.get("6").toString().compareTo(o2.get("6").toString()) > 0)
                            return 1;
                        else if(o1.get("6").toString().compareTo(o2.get("6").toString()) == 0)
                            return 0;
                        else return -1;
                    }
                };
            }

            Collections.sort(JSONObjects, comparator);

            for (JSONObject jso : JSONObjects) {
                JSONObject jso1 = new JSONObject();
                for(int i=0;i<excelMap.size();++i){
                    String val = String.valueOf(jso.get(String.valueOf(i)));
                    jso1.put(excelMap.get(String.valueOf(i+1)), val);
                }
                System.out.println(JSON.toJSONString(jso1));

                sb.append(JSON.toJSONString(jso1));
                sb.append('\n');
            }

            fileName = fileName.substring(0, fileName.length()-4);
            OutputStream os = new FileOutputStream("C:\\workspace\\settle-line-comparison\\" + fileName + ".txt");
            os.write(sb.toString().getBytes(StandardCharsets.UTF_8));
            os.flush();
            os.close();

        }catch (Exception e) {
            e.printStackTrace();
        }

        

        return "success";
    }

    private void load(){
        permissionList=permissionMapper.selectAll();
        moduleList=moduleMapper.selectAll();
        resourceList=resourceMapper.selectAll();
    }

}
